"""
路由管理器
"""
from tests.utils.logUtil import log


class RouteManager:
    """
    用于生成和检索路线的路线管理实用程序.
    """

    def __init__(self):
        self.prefix_mapping = {}

    def register_module(self, module_name: str, prefix: str):
        """
        注册一个模块及其路由前缀.
        """
        if not module_name or not prefix:
            raise ValueError("Module name and prefix cannot be empty.")
        if not isinstance(module_name, str) or not isinstance(prefix, str):
            raise ValueError("Module name and prefix must be strings.")

        self.prefix_mapping[module_name.lower()] = prefix

    def get_prefix(self, module_name: str) -> str:
        """
        获取模块对应的路由前缀. 如果未注册，返回默认值.
        :module_name (str): 模块名称.
        :return str: 模块的路由前缀.
        """
        if not module_name or not isinstance(module_name, str):
            raise ValueError("Module name must be a non-empty string.")

        prefix = self.prefix_mapping.get(module_name.lower(), f"/{module_name.lower()}")
        log.info(f"Retrieved prefix for module '{module_name}': '{prefix}'")
        return prefix

    def generate_route(self, module_name: str, path: str = "", **kwargs) -> str:
        """
        根据模块名称、附加路径和参数生成完整路由.
        :param module_name: 模块名称.
        :type module_name: str
        :param path: 附加路径.
        :type path: str
        :param kwargs: 路径中的命名参数（例如 {id}, {name}）.
        :type kwargs: dict
        :returns: 完整的路由.
        :rtype: str
        """
        if not isinstance(module_name, str) or not isinstance(path, str):
            raise ValueError("Module name and path must be strings.")
        prefix = self.get_prefix(module_name)
        route = f"{prefix}/{path}".strip("/")
        # log.info(f"RouteManager generate_route: {route}")

        if kwargs:
            # 替换路径占位符为实际参数值
            for key, value in kwargs.items():
                if not isinstance(key, str) or not isinstance(value, (str, int, float)):
                    raise ValueError("Key and value in kwargs must be strings or numbers.")
                route = route.replace(f"{{{key}}}", str(value))

        log.info(f"Generated route for module '{module_name}': '{route}'")
        return route


# 全局单例实例
route_manager = RouteManager()
